package com.superpai.view.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

import com.superpai.common.Constants;
import com.superpai.domain.DBProduct;

/**
 * @author Devin.Hu
 * @date 2011-8-24
 * @version V1.0
 * @description 我的收藏数据库辅助类
 */
public class MyStoreDBHelper extends BaseDBHelper {

	public MyStoreDBHelper(Context context) {
		super(context, Constants.DBNAME, null, Constants.VERSION);
	}

	public MyStoreDBHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}
	
	/**
	 * 保存商品
	 * @param p
	 */
	public boolean saveItem(DBProduct p) {
		boolean flag = true;
		SQLiteDatabase db = getReadableDatabase();
		Cursor cs = db.rawQuery("select count(*) from mystore where pcode = ? ", new String[]{p.getPcode()});
		cs.moveToFirst();
		if (cs.getLong(0) > 0 ) {
			flag = false;
		}
		cs.close();
		
		if(flag){
			db = getWritableDatabase();
			db.execSQL("insert into mystore (pcode , pname , price , pimg) values (?, ? , ? , ?)", new Object[] { p.getPcode(), p.getPname(), p.getPrice(), p.getPimg() });
			db.close();
		}
		return flag;
	}
	
	/**
	 * 根据商品编码查询商品信息
	 * @param id
	 * @return
	 */
	public DBProduct findItemByPcode(String pcode) {
		DBProduct item = new DBProduct();
		SQLiteDatabase db = getReadableDatabase();
		Cursor cs = db.rawQuery("select * from mystore where pcode = ? ", new String[]{pcode});
		if(cs.moveToFirst()) {
			item.setPcode(cs.getString(cs.getColumnIndex("pcode")));
			item.setPname(cs.getString(cs.getColumnIndex("pname")));
			item.setPrice(cs.getString(cs.getColumnIndex("price")));
			item.setPimg(cs.getString(cs.getColumnIndex("pimg")));
		}
		cs.close();
		db.close();
		return item;
	} 
	
	/**
	 * 查询商品列表信息
	 * @param id
	 * @return
	 */
	public List<DBProduct> findItemList() {
		DBProduct item = null;
		List<DBProduct> mList = new ArrayList<DBProduct>();
		SQLiteDatabase db = getReadableDatabase();
		Cursor cs = db.rawQuery("select * from mystore ", null);
		
		while(cs.moveToFirst()) {
			item = new DBProduct();
			item.setPcode(cs.getString(cs.getColumnIndex("pcode")));
			item.setPname(cs.getString(cs.getColumnIndex("pname")));
			item.setPrice(cs.getString(cs.getColumnIndex("price")));
			item.setPimg(cs.getString(cs.getColumnIndex("pimg")));
			mList.add(item);
		}
		cs.close();
		db.close();
		return mList;
	} 
}
